package com.zone.domain.award.service;

import com.alibaba.fastjson2.JSON;
import com.zone.domain.award.event.UserWinAwardEvent;
import com.zone.domain.award.model.aggregate.UserAwardRecordAggregate;
import com.zone.domain.award.model.entity.AwardEntity;
import com.zone.domain.award.model.entity.DistributeAwardEntity;
import com.zone.domain.award.model.entity.UserAwardRecordEntity;
import com.zone.domain.award.repository.IAwardRepository;
import com.zone.domain.award.service.distribute.IDistributeAwardService;
import com.zone.domain.common.factory.SimpleFactory;
import com.zone.domain.task.model.entity.TaskEntity;
import com.zone.domain.task.model.valobj.TaskState;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2025/2/22
 */
@Slf4j
@Service
public class AwardServiceImpl implements IAwardService {
    @Autowired
    private IAwardRepository awardRepository;
    /** 消息主题 */
    @Value("${spring.rabbitmq.topic.user_win_award}")
    private String userWinAwardTopic;

    @Override
    public void saveUserAwardRecord(UserAwardRecordEntity userAwardRecordEntity) {
        // 构造聚合对象
        UserAwardRecordAggregate userAwardRecordAggregate = new UserAwardRecordAggregate();
        userAwardRecordAggregate.setUserAwardRecordEntity(userAwardRecordEntity);

        // 用户中奖消息
        UserWinAwardEvent userWinAwardEvent = new UserWinAwardEvent();
        userWinAwardEvent.setUserId(userAwardRecordEntity.getUserId());
        userWinAwardEvent.setActivityId(userAwardRecordEntity.getActivityId());
        userWinAwardEvent.setAwardId(userAwardRecordEntity.getAwardId());
        userWinAwardEvent.setOrderId(userAwardRecordEntity.getOrderId());
        userWinAwardEvent.setAwardConfig(userAwardRecordEntity.getAwardConfig());
        // 任务实体
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setUserId(userAwardRecordEntity.getUserId());
        taskEntity.setTopic(userWinAwardTopic);
        taskEntity.setMessageId(RandomStringUtils.randomNumeric(11));
        taskEntity.setMessage(JSON.toJSONString(userWinAwardEvent));
        taskEntity.setState(TaskState.CREATE);
        userAwardRecordAggregate.setTaskEntity(taskEntity);
        // 保存用户中奖记录
        awardRepository.saveUserAwardRecord(userAwardRecordAggregate);
    }

    @Override
    public void distribute(DistributeAwardEntity distributeAwardEntity) {
        AwardEntity awardEntity = awardRepository.queryAward(distributeAwardEntity.getAwardId());
        if (Objects.isNull(awardEntity)) {
            log.info("奖品分发失败，未查询到奖品信息，awardId = {}", distributeAwardEntity.getAwardId());
            return;
        }
        SimpleFactory<IDistributeAwardService> distributeAwardFactory = new SimpleFactory<>(IDistributeAwardService.class);
        IDistributeAwardService handler = distributeAwardFactory.newInstance(awardEntity.getAwardKey());
        if (Objects.isNull(handler)) {
            log.info("奖品分发失败，未查询到发奖处理器，handlerName = {}", awardEntity.getAwardKey());
            return;
        }
        try {
            // 调用处理器执行发奖
            handler.executeHandOutPrizes(distributeAwardEntity);
        } catch (Exception e) {
            log.error("奖品分发失败，发奖处理器异常，handlerName = {}", awardEntity.getAwardKey(), e);
        }
    }

    @Override
    public UserAwardRecordEntity queryUserAwardRecord(String userId, String orderId) {
        return awardRepository.queryUserAwardRecord(userId, orderId);
    }
}
